package com.guocloud.medimind.controller;

import com.guocloud.medimind.utils.TextMedicalRecordExtractor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 文本提取API控制器
 */
@RestController
@RequestMapping("/api/extract")
@Slf4j
public class TextExtractionController {

    @Autowired
    private TextMedicalRecordExtractor textExtractor;

    /**
     * 从文本内容提取JSON
     * @param textContent 文本内容
     * @return JSON结果
     */
    @PostMapping(value = "/text", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> extractFromText(@RequestBody String textContent) {
        log.info("接收文本提取请求，内容长度: {}", textContent.length());
        String jsonResult = textExtractor.extractMedicalRecordToJson(textContent);
        return ResponseEntity.ok(jsonResult);
    }

    /**
     * 从TXT文件提取JSON
     * @param file 上传的TXT文件
     * @return JSON结果
     */
    @PostMapping(value = "/file", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> extractFromFile(@RequestParam("file") MultipartFile file) {
        try {
            log.info("接收文件提取请求，文件名: {}, 大小: {}", file.getOriginalFilename(), file.getSize());

            // 从文件读取内容
            String content = new String(file.getBytes(), StandardCharsets.UTF_8);
            String jsonResult = textExtractor.extractMedicalRecordToJson(content);

            return ResponseEntity.ok(jsonResult);
        } catch (IOException e) {
            log.error("文件处理失败", e);
            return ResponseEntity.badRequest().body("{\"error\": \"" + e.getMessage() + "\"}");
        }
    }
}